package com.youboy.wechatapi.service.record.impl;

import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youboy.wechatapi.domain.mysql.UserInfo;
import com.youboy.wechatapi.repository.message.UserRepository;
import com.youboy.wechatapi.service.record.UserService;
import com.youboy.wechatapi.utils.json.JacksonMapper;
import com.youboy.wechatapi.utils.wechat.WechatApi;

/**
 * @ProjectName：wechatapi
 * @author：冉尧（Yvan）
 * @CreateTime：2014年10月28日 上午11:03:41
 * @Remarks：
 */
@Service
public class UserServiceImpl implements UserService {
	
	private Logger log = Logger.getLogger(UserServiceImpl.class);

	@Autowired
	private UserRepository userRepository;

	@Override
	public void saveUserInfo(String openid) throws Exception {
		String userInfoJson = WechatApi.getUserInfo(openid);

		if (StringUtils.isBlank(userInfoJson) || userInfoJson.contains("errcode")) {
			return;
		}

		UserInfo userInfo = JacksonMapper.getInstance().readValue(userInfoJson, UserInfo.class);
		if(userInfo != null){
			userInfo.setNickname(this.getUtf8Str(userInfo.getNickname()));
			userRepository.save(userInfo);
		}
	}

	@Override
	public void saveUserInfo(UserInfo userInfo) throws Exception {
		userRepository.save(userInfo);
	}

	private String getUtf8Str(String str) {
		try {
			str = new String(str.getBytes("utf-8"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("[nickname:" + str + "] change code to utf-8 error !", e);
			str = null;
		}
		return str;
	}

}
